package com.kristin.proxy.aop.sync;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName JdkAopTest
 * @Description TODO
 * @Author Kristin
 * @Date 2020/09/17 11:36:15
 * @Version 1.0.0
 */
public class JdkAopTest {

    public static Object getGeneralJdkAop(UserServer userServer , IPoint iPoint) {
        return Proxy.newProxyInstance(userServer.getClass().getClassLoader(), userServer.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("jdk代理");
                iPoint.before();
                Object result = method.invoke(userServer , args);
                iPoint.after();
                return result;
            }
        });
    }

    public static Object getGeneralCglibAop(UserServer userServer , IPoint iPoint) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(userServer.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("cglib代理");
                iPoint.before();
                Object result = method.invoke(userServer, objects);
                iPoint.after();
                return result;
            }
        });
        return enhancer.create();
    }


    public static void main(String[] args) {
//        UserServer userServer = new UserServiceImpl();
//        userServer.saveUser();
//        UserServer userServer = (UserServer)getGeneralJdkAop(new UserServiceImpl() , new PointImpl());
//        userServer.saveUser();
        UserServer userServer = (UserServer)getGeneralCglibAop(new UserServiceImpl() , new PointImpl());
        userServer.saveUser();
        // 静态AOP代理，使用AOP框架提供的命令进行编译，从而在编译阶段通过AOP框架指令生成AOP动态代理类，因此被称为编译时增强
        // 动态代理则在运行时借助JDK动态代理、CGlib等在内存中临时生成AOP动态代理类，因此也被称为运行时增强

    }


}


